package auth

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/captcha"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/logger"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/verifycode"
	"github.com/gofiber/fiber/v2"
)

// VerifyCodeController 用户控制器
type VerifyCodeController struct {
	v1.BaseController
}

// ShowCaptcha 显示图片验证码
func (controller *VerifyCodeController) ShowCaptcha(c *fiber.Ctx) error {
	// 生成验证码
	id, b64s, err := captcha.NewCaptcha().GenerateCaptcha()
	// 记录错误日志，因为验证码是用户的入口，出错时应该记 error 等级的日志
	logger.LogIf(err)
	// 返回给用户
	return controller.Json(c, map[string]interface{}{
		"captcha_id":    id,
		"captcha_image": b64s,
	})
}

// SendUsingPhone 发送手机验证码
func (controller *VerifyCodeController) SendUsingPhone(c *fiber.Ctx) error {

	request := new(requests.VerifyCodePhoneRequest)

	if errors := requests.VerifyCodePhone(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	// 2. 发送 SMS
	if ok := verifycode.New().SendSMS(request.Phone); !ok {
		return controller.Faield(c, "发送短信失败~")
	} else {
		return controller.Success(c)
	}
}

// SendUsingPhone 发送手机验证码
func (controller *VerifyCodeController) SendUsingEmail(c *fiber.Ctx) error {

	request := new(requests.VerifyCodeEmailRequest)

	if errors := requests.VerifyCodeEmail(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	// 2. 发送 SMS
	if ok := verifycode.New().SendEmail(request.Email); !ok {
		return controller.Faield(c, "发送验证码失败~")
	} else {
		return controller.Success(c)
	}
}
